package org.tong.net;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public abstract class SelectorThread extends Thread {

    private Selector selector;

    public SelectorThread() throws IOException {
        this.selector = Selector.open();
    }

    @Override
    public void run() {
        while (true) {
            if (this.isInterrupted()) {
                break;
            }
            try {
                int n = selector.select();
                if (n > 0) {
                    for (SelectionKey selectionKey : selector.selectedKeys()) {
                        handleSelectionKey(selectionKey);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    abstract void handleSelectionKey(SelectionKey selectionKey);

    public final Selector getSelector(){
        return this.selector;
    }

    public boolean addChannel(SocketChannel socketChannel, int ops) {
        try {
            socketChannel.register(this.selector, ops);
            return true;
        } catch (ClosedChannelException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void close() {
        this.interrupt();
    }
}
